import { View, Text, StyleSheet, FlatList, TouchableOpacity, RefreshControl } from 'react-native';
import { useState, useCallback, useEffect } from 'react';
import { useRouter } from 'expo-router';
import { communityService } from '../../utils/api/services';
import { TopicResponse } from '../../utils/api/types';
import { MaterialIcons } from '@expo/vector-icons';
import { formatDate } from '../../utils/date';
import { useTheme } from '../../components/theme/ThemeContext';

export default function CommunityScreen() {
  const router = useRouter();
  const { theme } = useTheme();
  const [topics, setTopics] = useState<TopicResponse[]>([]);
  const [refreshing, setRefreshing] = useState(false);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  const fetchTopics = useCallback(async (pageNum = 1) => {
    try {
      setLoading(true);
      const response = await communityService.listTopics({ page: pageNum, size: 10 });
      
      const topicsData = response?.data?.data;
      if (Array.isArray(topicsData)) {
        if (pageNum === 1) {
          setTopics(topicsData);
        } else if (topicsData.length > 0) {
          setTopics(prev => [...prev, ...topicsData]);
        }
        if (topicsData.length > 0) {
          setPage(pageNum);
        }
      }
    } catch (error) {
      console.error('获取话题列表失败:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchTopics(1);
  }, [fetchTopics]);

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    fetchTopics(1);
  }, [fetchTopics]);

  const renderTopicItem = ({ item }: { item: TopicResponse }) => (
    <TouchableOpacity 
      style={[styles.topicItem, { backgroundColor: theme.colors.card }]}
      onPress={() => router.push({ pathname: '/topic/[id]', params: { id: item.id } })}
    >
      <Text style={[styles.topicTitle, { color: theme.colors.text }]}>{item.title}</Text>
      <Text style={[styles.topicContent, { color: theme.colors.placeholder }]} numberOfLines={2}>{item.content}</Text>
      <View style={styles.topicFooter}>
        <Text style={[styles.topicDate, { color: theme.colors.placeholder }]}>{formatDate(item.created_at)}</Text>
      </View>
    </TouchableOpacity>
  );

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
      <View style={[styles.header, { backgroundColor: theme.colors.card, borderBottomColor: theme.colors.border }]}>
        <Text style={[styles.title, { color: theme.colors.text }]}>社区讨论</Text>
      </View>

      {topics.length === 0 ? (
        <View style={styles.emptyContainer}>
          <Text style={[styles.emptyText, { color: theme.colors.placeholder }]}>
            还没有任何话题，快来发布第一个话题吧！
          </Text>
        </View>
      ) : (
        <FlatList
          data={topics}
          renderItem={renderTopicItem}
          keyExtractor={item => item.id.toString()}
          refreshControl={
            <RefreshControl 
              refreshing={refreshing} 
              onRefresh={onRefresh}
              colors={[theme.colors.primary]}
              tintColor={theme.colors.primary}
            />
          }
          onEndReached={() => {
            if (!loading && topics.length >= page * 10) {
              fetchTopics(page + 1);
            }
          }}
          onEndReachedThreshold={0.5}
          style={styles.list}
        />
      )}

      <TouchableOpacity 
        style={[styles.fab, { backgroundColor: theme.colors.primary }]}
        onPress={() => router.push('/topic/create' as any)}
      >
        <MaterialIcons name="add" size={24} color="#fff" />
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  fab: {
    position: 'absolute',
    right: 20,
    bottom: 20,
    width: 56,
    height: 56,
    borderRadius: 28,
    alignItems: 'center',
    justifyContent: 'center',
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
  },
  list: {
    flex: 1,
  },
  topicItem: {
    padding: 16,
    marginVertical: 8,
    marginHorizontal: 16,
    borderRadius: 8,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  topicTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  topicContent: {
    fontSize: 14,
    marginBottom: 8,
  },
  topicFooter: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  topicDate: {
    fontSize: 12,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16,
  },
  emptyText: {
    fontSize: 16,
    textAlign: 'center',
  },
}); 